package com.ibm.rules;

import java.math.BigInteger;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;

import com.ibm.interfaces.ITimeSeriesSchema;
import com.ibm.util.ErrorCode;
import com.ibm.util.exception.CPSException;

/**
 * 
 * @author yaoliang Chen Given a rule string(String ruleString), and give it a
 *         ruleid(BigInteger ruleId), and its related stream data source's
 *         schema(ITimeSeriesSchema tags) we build a vector of Rule for
 *         ruleString(see RuleParser#parseRule)
 * 
 *         Note that: each Rule[i] is parsed as a part of ruleString and
 *         splitted by relation "OR"(See class RuleExpressionVisitor) for
 *         example: ruleString = "tag2>1 and tag3 < 3 or tag3>1 and tag3 < 3" is
 *         parsed into Rule[0],Rule[1] Rule[0]: tag2>1 and tag3 < 3 Rule[1]:
 *         tag3>1 and tag3 < 3" And for each Rule[i]'s condition string part, it
 *         is further splitted into RuleEntry limitation: each ruleentry
 *         currently is a condition expression of "tagX >/>=.... #constant', so
 *         each RuleEntry can be mapped to an unique tag id index
 */
public class RuleParser {
	static public Rule[] parseRule(ITimeSeriesSchema tags, BigInteger ruleId, String ruleString) throws CPSException {
		Expression exp;
		try {
			exp = CCJSqlParserUtil.parseCondExpression(ruleString);
			RuleExpressionVisitor visitor = new RuleExpressionVisitor(tags, ruleId);
			exp.accept(visitor);
			return visitor.getRules();
		} catch (JSQLParserException e) {
			throw new CPSException(ErrorCode.PARSE_ERROR_CODE, "Invalid character in rule " + ruleString);
		}
	}

	public static void main(String[] args) throws JSQLParserException {
		String rule = "Not (a+b)*x>10";
		Expression exp = CCJSqlParserUtil.parseCondExpression(rule);
		System.out.println(exp);

	}
}
